package cn.com.tarotframework.listener;

import cn.com.tarotframework.server.workflow.eu.FlowEvents;
import cn.com.tarotframework.server.workflow.eu.FlowStatus;
import cn.com.tarotframework.server.workflow.po.FlowNode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.Message;
import org.springframework.statemachine.annotation.OnTransition;
import org.springframework.statemachine.annotation.WithStateMachine;
import org.springframework.stereotype.Component;


/**
 * 添加流程状态监听
 */
@Slf4j
@Component
@WithStateMachine
public class FlowNodeLister {


    /**
     * 执行成功，更新状态
     * @param message 消息
     * @return boolean
     */
    @OnTransition(source = "EXECUTE_WAIT", target = "EXECUTE_SUCCESS")
    public boolean executeSuccess(Message<FlowEvents> message) {
        FlowNode flowNode = (FlowNode) message.getHeaders().get("flowNode");
        assert flowNode != null;
        flowNode.setStatus(FlowStatus.EXECUTE_SUCCESS);
        log.info("---线程分组："+Thread.currentThread().getThreadGroup().getName()+"，线程名称："+Thread.currentThread().getName()+" 节点【{}-{}】执行成功，状态机反馈信息【{} --> {}】", flowNode.getId(), flowNode.getName(), FlowStatus.EXECUTE_WAIT, FlowStatus.EXECUTE_SUCCESS);
        return true;
    }

    /**
     * 执行失败，更新状态
     * @param message 消息
     * @return boolean
     */
    @OnTransition(source = "EXECUTE_WAIT", target = "EXECUTE_ERROR")
    public boolean executeFail(Message<FlowEvents> message) {
        FlowNode flowNode = (FlowNode) message.getHeaders().get("flowNode");
        assert flowNode != null;
        flowNode.setStatus(FlowStatus.EXECUTE_ERROR);
        log.info("---线程分组："+Thread.currentThread().getThreadGroup().getName()+"，线程名称："+Thread.currentThread().getName()+" 节点【{}-{}】执行失败，状态机反馈信息【{} --> {}】", flowNode.getId(), flowNode.getName(), FlowStatus.EXECUTE_WAIT, FlowStatus.EXECUTE_ERROR);
        return true;
    }

    /**
     * 执行失败，更新状态
     * @param message 消息
     * @return boolean
     */
    @OnTransition(source = "EXECUTE_WAIT", target = "EXECUTE_NOT")
    public boolean executeStop(Message<FlowEvents> message) {
        FlowNode flowNode = (FlowNode) message.getHeaders().get("flowNode");
        assert flowNode != null;
        flowNode.setStatus(FlowStatus.EXECUTE_NOT);
        log.info("---线程分组："+Thread.currentThread().getThreadGroup().getName()+"，线程名称："+Thread.currentThread().getName()+" 节点【{}-{}】没有执行，状态机反馈信息【{} --> {}】", flowNode.getId(), flowNode.getName(), FlowStatus.EXECUTE_WAIT, FlowStatus.EXECUTE_NOT);
        return true;
    }

}
